package api;

import model.Article;
import model.ArticleDao;
import model.User;
import model.UserDao;
import view.HtmlGenerator;

import javax.jws.soap.SOAPBinding;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class DeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 验证登录
        // 1.判定登录状态
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession(false);
        resp.setContentType("text/html; charset=utf-8");
        if(session == null){// 说明没 登录 (那就不能到这个页面);
            String html = HtmlGenerator.getMessagePage("请先登录","login.html");
            resp.getWriter().write(html);
            return ;
        }
        // 2. 读取亲求删除 id
        String articleId = req.getParameter("articleId");
        if(articleId == null || "".equals(articleId)){
            String html = HtmlGenerator.getMessagePage("要删除的文章id 有误","article");
            resp.getWriter().write(html);
            return ;
        }
        // 3. 根据文章id 作者是你才能删;
        UserDao userDao = new UserDao();
        ArticleDao articleDao = new ArticleDao();
        Article article = articleDao.selectById(Integer.parseInt(articleId));
        if(article == null){// 文章不存在
            String html = HtmlGenerator.getMessagePage("要删除的文章不存在","article");
            resp.getWriter().write(html);
            return ;
        }
        User user = (User) session.getAttribute("user");
        if(article.getUserId() != user.getUserId()){
            String html = HtmlGenerator.getMessagePage("请不要强行删除别人的文章","article");
            resp.getWriter().write(html);
            return ;
        }
        articleDao.delete(Integer.parseInt(articleId));
        String html = HtmlGenerator.getMessagePage("删除成功!","article");
        resp.getWriter().write(html);
    }
}
